package com.example.obtaingaode.util;

import android.os.Environment;

import com.google.gson.Gson;
import com.orhanobut.logger.Logger;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

/**
 * Created by Ma.Chong on 2017/10/26.
 */

public class ExeclUtil {
    public static final String fileName="yiganyidian.xls";
    /**
     *
     * @param datas 数据对象集合
     */
    public <T> String save(Class<T> cls, List<T> datas) {
        String name = cls.getName().substring(cls.getName().lastIndexOf(".")+1);
        //创建工作簿
        WritableWorkbook workbook=null;
        try {
            String path = Environment.getExternalStorageDirectory().getPath();
            workbook = Workbook.createWorkbook(new File(path,fileName));
            WritableSheet sheet = workbook.createSheet(name, 0);
            for (int i = 0; i < datas.size(); i++) {
                save(datas.get(i),sheet,i);
            }
            Logger.d("数据存储完毕,存储路径是 %s/%s,存储了%s条数据",path,fileName,""+datas.size());
            return String.format("数据存储完毕,存储路径是 %s/%s,存储了%s条数据",path,fileName,""+datas.size());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (workbook != null)
            {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (WriteException e) {
                    e.printStackTrace();
                }
            }
        }
        return  null;
    }
    public <T> void save(T data,WritableSheet sheet,int position){
        try {
            JSONObject jb = new JSONObject(new Gson().toJson(data));
            Iterator<String> keys = jb.keys();
            int i=1;
            while (keys.hasNext()) {
                Label label = new Label(i, position, jb.getString(keys.next()));
                i++;
                try {
                    sheet.addCell(label);
                } catch (WriteException e) {
                    e.printStackTrace();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
